package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;


/**
 * @author 高杰  gao4433@qq.com
 * @Description
 * @date 2021/12/13 14:48
 * @since 1.8
 */
public class LoginFilter implements Filter {

    /**
     * 初始化函数
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 过滤器被销毁时执行
     */
    @Override
    public void destroy() {

    }

    /**
     * 执行拦截的逻辑代码
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将 req 强制类型转换为 HttpServletRequest 对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 将 resp 强制类型转换为 HttpServletResponse 对象
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // getRequestURI 方法得到的是：/wyl/login.jsp
        // request.getRequestURI();
        // getRequestURL 方法得到的是：http://localhost:8080/wyl/login.jsp
        // request.getRequestURL();
        String uri = request.getRequestURI();

        HashSet<String> set = new HashSet<>();
        set.add("/login.jsp");
        set.add("/login");
        set.add("/login_error.jsp");
        set.add("/code_error.jsp");

        if ( set.contains(uri) || uri.endsWith(".css") || uri.endsWith(".img") || uri.startsWith("/code") ) {
            // 此时被拦截的是登录页或样式表，允许通过
            filterChain.doFilter(request, response);
            return;
        }

/*        if ("/login.jsp".equals(uri) ||"/login".equals(uri) || "/login_error.jsp".equals(uri) || "/code_error.jsp".equals(uri) || uri.endsWith(".css") || uri.endsWith(".img") || uri.startsWith("/code") ) {
            // 此时被拦截的是登录页或样式表，允许通过
            filterChain.doFilter(request, response);
            return;
        }*/

        // 获取 session
        HttpSession session = request.getSession();
        Object uid = session.getAttribute("UID");
        if (uid == null) {
            // 说明没有登录
            response.sendRedirect("/login_error.jsp");
            return;
        }

        // 说明用户已经登录过，允许通过
        filterChain.doFilter(request, response);
    }

}
